package net.leieuncretino.beta.parole;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Set;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

import net.leieuncretino.beta.parole.impl.Partita;
import net.leieuncretino.beta.parole.ui.TabelloneView;
import net.leieuncretino.beta.prefixtree.Trie;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;

public class ParoleScoreActivity extends TabActivity {
	
    private AdView ad = null;
    public static final boolean debug = ParoleActivity.debug;
	

	private static final String TAG = "ParoleScoreActivity";

	public static final String DEFINE_URL = 
		"http://www.google.com/search?q=define%3a+";

	private Partita game;
	private TabelloneView bv;
	private View highlighted;
	
	public ParoleApp getApp() {
		 return ((ParoleApp)getApplicationContext());
	}
	

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
     	super.onCreate(savedInstanceState);

     	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
     	
     	
		if(savedInstanceState != null) {
			// game = new Partita(this, savedInstanceState);
			game = getApp().getPartita(this, savedInstanceState);

		} else {
			Intent intent = getIntent();
			Bundle bun = intent.getExtras();
			// game = new Partita(this,bun);
			game = getApp().getPartita(this, bun);
		}
// Already invoked		game.initializeDictionary();

		// Tabs
		TabHost host = getTabHost();
		LayoutInflater.from(this).inflate(R.layout.punteggio,
			host.getTabContentView(), true);

		Method m = null;
		try {
			m = TabSpec.class.getMethod("setIndicator",new Class[] { TextView.class });
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		boolean doneTab = false;
		if (m != null) {
		
			try {
				TextView tview=new TextView(this); 
				tview.setText(R.string.found_words);
				tview.setHeight(30);
				TabSpec ts = host.newTabSpec("found");
				m.invoke(ts, tview);
				host.addTab(ts.setContent(R.id.found_words));
				
				
				tview=new TextView(this); 
				tview.setText(R.string.missed_words);
				tview.setHeight(30);
				ts = host.newTabSpec("missed");
				m.invoke(ts, tview);
				host.addTab(ts.setContent(R.id.missed_words));
				
				
				doneTab = true;
				
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (!doneTab) {
			host.addTab(host.newTabSpec("found").setIndicator(getString(R.string.found_words)).
					setContent(R.id.found_words));
			host.addTab(host.newTabSpec("missed").setIndicator(getString(R.string.missed_words)).
					setContent(R.id.missed_words));
			
			for (int i = 0; i < 2; i++) {
			    host.getTabWidget().getChildAt(i).getLayoutParams().height = 30;
			}
		}
		
		
		bv = (TabelloneView) findViewById(R.id.missed_board);
		bv.setBoard(game.getBoard());

		Set<String> possible = game.getSolutions().keySet();

		ViewGroup foundVG = initializeScrollView(R.id.found_scroll);
		ViewGroup missedVG = initializeScrollView(R.id.missed_scroll);

		int score = 0;
		int max_score = 0;
		int words = 0;
		int max_words = possible.size();

		Iterator<String> li = game.uniqueListIterator();
		while(li.hasNext()) {
			String w = li.next();

			if(game.isWord(w) && Partita.PUNTI[w.length()] > 0) {
				int points = Partita.PUNTI[w.length()];
				addWord(foundVG,w,points,0xff000000,true);
				score += Partita.PUNTI[w.length()];
				words++;
			} else {
				addWord(foundVG,w,0,0xffff0000,false);
			}

			// possible.remove(w);
		}
	
		max_score = score;
		li = possible.iterator();

		while(li.hasNext()) {
			String w = li.next();
			if (!game.isFound(w)) {
				max_score += Partita.PUNTI[w.length()];
				addMissedWord(missedVG,game.getSolutions().get(w));
			}
		}
		
// WAS		
//		Iterator<String> li = game.uniqueListIterator();
//		while(li.hasNext()) {
//			String w = li.next();
//
//			if(game.isWord(w) && game.WORD_POINTS[w.length()] > 0) {
//				int points = Partita.WORD_POINTS[w.length()];
//				addWord(foundVG,w,points,0xff000000,true);
//				score += game.WORD_POINTS[w.length()];
//				words++;
//			} else {
//				addWord(foundVG,w,0,0xffff0000,false);
//			}
//
//			possible.remove(w);
//		}
//	
//		max_score = score;
//		li = possible.iterator();
//
//		while(li.hasNext()) {
//			String w = li.next();
//			max_score += game.WORD_POINTS[w.length()];
//			addMissedWord(missedVG,game.getSolutions().get(w));
//		}

		TextView t = (TextView) findViewById(R.id.score_points);
		t.setText(""+score+"/"+max_score);

		t = (TextView) findViewById(R.id.score_words);
		t.setText(""+words+"/"+max_words);

		Button b = (Button) findViewById(R.id.close_score);
		b.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});

		b = (Button) findViewById(R.id.missed_close_score);
		b.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		
        ad = (AdView)findViewById(R.id.ad);
		

	}
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	// TODO Auto-generated method stub
    	super.onConfigurationChanged(newConfig);
        ad = (AdView)findViewById(R.id.ad);
    }

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		game.save(outState);
	}

	private ViewGroup initializeScrollView(int resId) {
		ScrollView sv = (ScrollView) findViewById(resId);
		sv.setScrollBarStyle(sv.SCROLLBARS_OUTSIDE_INSET);

		ViewGroup.LayoutParams llLp = new ViewGroup.LayoutParams(
			ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.WRAP_CONTENT);

		LinearLayout ll = new LinearLayout(this);
		ll.setLayoutParams(llLp);
		ll.setOrientation(LinearLayout.VERTICAL);
		sv.addView(ll);

		return ll;
	}

	private void addWord(ViewGroup vg, String w, int points, int color,
		boolean link) {
		LinearLayout.LayoutParams text1Lp = new LinearLayout.LayoutParams(
			ViewGroup.LayoutParams.WRAP_CONTENT,
			ViewGroup.LayoutParams.WRAP_CONTENT,
			(float) 1.0);
		TextView tv1 = new TextView(this);
		tv1.setGravity(Gravity.LEFT);
		tv1.setLayoutParams(text1Lp);
		tv1.setTextSize(16);
		tv1.setTextColor(color);
		tv1.setText(w);

		LinearLayout.LayoutParams text2Lp = new LinearLayout.LayoutParams(
			ViewGroup.LayoutParams.WRAP_CONTENT,
			ViewGroup.LayoutParams.WRAP_CONTENT);
		TextView tv2 = new TextView(this);
		tv2.setGravity(Gravity.RIGHT);
		tv2.setLayoutParams(text2Lp);
		tv2.setTextSize(16);
		tv2.setTextColor(color);
		tv2.setText(""+points+" ");

		LinearLayout ll = new LinearLayout(this);
		ll.setOrientation(LinearLayout.HORIZONTAL);

		ll.addView(tv1);

		if(link) {
			TextView tv3 = new TextView(this);
			tv3.setGravity(Gravity.RIGHT);
			tv3.setLayoutParams(text2Lp);
			tv3.setTextSize(16);
			tv3.setTextColor(0xff000000);
			tv3.setText(R.string.define_word);

			tv3.setOnClickListener(new DefinerListener(w));
			tv3.setFocusable(true);

			ll.addView(tv3);
		}

		ll.addView(tv2);

		vg.addView(ll, new LinearLayout.LayoutParams(
			ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.WRAP_CONTENT));

	}

	private void addMissedWord(ViewGroup vg, Trie.Solution solution) {
		String w = solution.getWord();

		LinearLayout ll = new LinearLayout(this);
		ll.setOrientation(LinearLayout.HORIZONTAL);

		ViewGroup.LayoutParams text1Lp = new LinearLayout.LayoutParams(
			ViewGroup.LayoutParams.WRAP_CONTENT,
			ViewGroup.LayoutParams.WRAP_CONTENT,
			(float) 1.0);
		TextView tv1 = new TextView(this);
		tv1.setGravity(Gravity.LEFT);
		tv1.setLayoutParams(text1Lp);
		tv1.setTextSize(16);
		tv1.setTextColor(0xff000000);
		tv1.setText(w);
		
		ViewGroup.LayoutParams text2Lp = new LinearLayout.LayoutParams(
			ViewGroup.LayoutParams.WRAP_CONTENT,
			ViewGroup.LayoutParams.WRAP_CONTENT);

		// Parola, link per evidenziare
		TextView tv2 = new TextView(this);
		tv2.setGravity(Gravity.RIGHT);
		tv2.setLayoutParams(text2Lp);
		tv2.setTextSize(16);
		tv2.setTextColor(0xff000000);
		tv2.setText(R.string.view_word);

		tv2.setOnClickListener(new HighlighterListener(solution.getMask(),
			ll));
		tv2.setFocusable(true);

		// Definizione (link)
		TextView tv3 = new TextView(this);
		tv3.setGravity(Gravity.RIGHT);
		tv3.setLayoutParams(text2Lp);
		tv3.setTextSize(16);
		tv3.setTextColor(0xff000000);
		tv3.setText(R.string.define_word);

		tv3.setOnClickListener(new DefinerListener(w));
		tv3.setFocusable(true);

		// Spazio fra i link
		TextView padding = new TextView(this);
		padding.setGravity(Gravity.RIGHT);
		padding.setLayoutParams(text2Lp);
		padding.setTextSize(16);
		padding.setText("        ");

		ll.addView(tv1);
		ll.addView(tv2);
		ll.addView(padding);
		ll.addView(tv3);
			
		vg.addView(ll, new LinearLayout.LayoutParams(
			ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.WRAP_CONTENT));
	}

	private class HighlighterListener implements View.OnClickListener {
		private long mask;
		private View parentView;

		private HighlighterListener(long mask, View parentView) {
			this.mask = mask;
			this.parentView = parentView;
		}

		public void onClick(View v) {
			bv.highlight(mask);
			bv.invalidate();

			if(highlighted != null) {
				highlighted.setBackgroundColor(0x00000000);
			}
			highlighted = parentView;
			highlighted.setBackgroundColor(0xffffff00);
		}
	}

	private class DefinerListener implements View.OnClickListener {
		String word;

		private DefinerListener(String word) {
			this.word = word;
		}

		public void onClick(View v) {
			Intent i = new Intent(Intent.ACTION_VIEW);
			Uri u = Uri.parse(DEFINE_URL+word);
			i.setData(u);
			startActivity(i);
		}
	}

	
	public void onPause() {
		super.onPause();
    	if (ad != null) {
    		ad.setEnabled(false);
    	}
		
	}

	public void onResume() {
		// Log.d(TAG, "SDK: " + android.os.Build.VERSION.SDK);
		super.onResume();
    	if (ad != null) {
    		ad.setEnabled(true);
			AdRequest req = new AdRequest();
			if (debug) {
				req.setTesting(true);
				req.addTestDevice(AdRequest.TEST_EMULATOR);
			}
			req.addKeyword("best");
			req.addKeyword("android");
			req.addKeyword("game");
			req.addKeyword("word");
			req.addKeyword("puzzle");
			req.addKeyword("casual");
			
			// android, android tool, settings, wifi, gps, bluetooth, brightness, battery, memory, sd card, plane, autorotate, synchronize			
			// Place keywords here
			ad.loadAd(req);
    	}
	}
	
}

